package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.ApUserLoginSuccessVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    /**
     * 用户登录
     *
     * @param apUser
     * @return {@link ApUserLoginSuccessVO}
     */
    @Override
    public ApUserLoginSuccessVO loginAuth(ApUser apUser) {
        if (StringUtils.isNoneBlank(apUser.getPhone(),apUser.getPassword())){
            //todo 正常用户登录
            ApUser apUserByPhone = baseMapper.selectOne(
                    Wrappers.lambdaQuery(ApUser.class)
                            .eq(ApUser::getPhone, apUser.getPhone())
            );
            if (Objects.isNull(apUserByPhone)) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String newPas = apUser.getPassword()+ apUserByPhone.getSalt();
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(newPas.getBytes());
            if (!Objects.equals(md5DigestAsHex,apUserByPhone.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            apUserByPhone.setPassword(null);
            apUserByPhone.setSalt(null);
            ApUserLoginSuccessVO apUserLoginSuccessVO = new ApUserLoginSuccessVO();
            String token = AppJwtUtil.generateToken(Long.valueOf(apUserByPhone.getId()));
            apUserLoginSuccessVO.setApUser(apUserByPhone);
            apUserLoginSuccessVO.setToken(token);
            return apUserLoginSuccessVO;
        }
        //todo 游客用户登录 -- 游客用户没有手机号和密码
        String token = AppJwtUtil.generateToken(0L);
        ApUserLoginSuccessVO apUserLoginSuccessVO = new ApUserLoginSuccessVO();
        apUserLoginSuccessVO.setApUser(null);
        apUserLoginSuccessVO.setToken(token);
        return  apUserLoginSuccessVO;
    }
}
